package com.gt.lib.twitter.example;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.gt.lib.twitter.TwitterApp;

public class TwitterExampleActivity extends Activity {

	final String TAG = "MainActivity";

	// --My Twitter key
	final String consumerKey = "qWGw3hCgXHqZ5wL72oC4Uw";
	final String secretKey = "XuVX8b8f8Nw82UCidiufjCEOXpd8thQpqlGGrMt4";
	final String callbackUrl = "http://www.twitter.com";

	private Button mTweet;
	private Button mClearAccessToken;

	private TwitterApp mTwitterApp;

	private Context mContext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;

		initView();

		configTwitter();

	}

	private void initView() {
		LinearLayout layout = new LinearLayout(mContext);
		layout.setOrientation(LinearLayout.VERTICAL);
		mTweet = new Button(mContext);
		mClearAccessToken = new Button(mContext);

		mTweet.setText("Tweet");
		mClearAccessToken.setText("Clear access token");

		layout.addView(mTweet);
		layout.addView(mClearAccessToken);
		setContentView(layout);
	}

	private void configTwitter() {
		 mTwitterApp = new TwitterApp(this, consumerKey, secretKey);

		mTweet.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mTwitterApp.hasAccessToken()) {
					mTwitterApp.authorize();
				} else {
					final EditText editText = new EditText(mContext);
					editText.setText("Tweet here");
					editText.setSelection(0, "Tweet here".length());
					new AlertDialog.Builder(mContext)
							.setTitle("What do you want to tweet?")
							.setView(editText)
							.setNegativeButton("Cancel", null)
							.setPositiveButton("Tweet",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											String message = editText.getText()
													.toString().trim();
											if (!"".equals(message)) {
												mTwitterApp.tweet(message);
											}
										}
									}).create().show();
				}
			}
		});

		mClearAccessToken.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mTwitterApp.resetAccessToken();
			}
		});
	}
}
